<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>前 K 个高频元素</title>
</head>
<body>
  <script>
    function fn(nums, k) {
      let map = new Map(), arr = [...new Set(nums)]
      nums.map((num) => {
        if (map.has(num)) map.set(num, map.get(num) + 1)
        else map.set(num, 1)
      })
      return arr.sort((a, b) => map.get(b) - map.get(a)).slice(0, k);
    }
    console.log(fn([1, 1, 1, 2, 2, 3], 2))
  </script>
</body>
</html>